package lock.reentrantLock;

import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 描述：演示锁的降级
 */
public class Upgrading {
    private static ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
    private static ReentrantReadWriteLock.ReadLock readLock = lock.readLock();
    private static ReentrantReadWriteLock.WriteLock writeLock = lock.writeLock();
    private static void writeDowngrading(){
        writeLock.lock();
        System.out.println("得到了writeLock，开始执行写操作");
        try {
            Thread.sleep(1000);
            readLock.lock();
            System.out.println("在不释放writeLock的情况下，获取readLock，成功降级");
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            readLock.unlock();
            System.out.println("释放readLock");
            writeLock.unlock();
            System.out.println("释放writeLock");
        }
    }

    public static void main(String[] args) {
        new Thread(Upgrading::writeDowngrading).start();
    }
}
